import { useSelector as useReduxSelector, TypedUseSelectorHook, useDispatch } from 'react-redux'
import languageReducer from './language'
import { todoSlice } from './todo/slice'
import { counterSlice } from './count/slice'
import thunkReducer from './thunk/reducer'
import { actionLog } from './middlewares/actionLog' // 自定义日志中间件
import { combineReducers, configureStore } from '@reduxjs/toolkit'

// 合并 reducer
export const rootReducer = combineReducers({
	language: languageReducer,
	todo: todoSlice.reducer, // 异步
	counter: counterSlice.reducer, // 同步
	todoThunk: thunkReducer // thunk
})

// 创建 store
// const store = createStore(rootReducer, applyMiddleware(thunk, actionLog))
const store = configureStore({
	reducer: rootReducer,
	// Redux Toolkit 的 configureStore 已经默认包含了 thunk 中间件
	middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(actionLog) // 中间件
	// devTools: true, // 扩展工具是否打开
})

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch // tokit 的 dispatch
export const useSelector: TypedUseSelectorHook<RootState> = useReduxSelector // 使用 useSelector 替代 useReduxSelector
export const useAppDispatch = () => useDispatch<AppDispatch>() // 使用 useAppDispatch 替代 useDispatch
export { store }
